package com.zlp.boot1.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: zhulaiping
 * @Date: 2021/11/2 13:52
 */
@WebFilter(urlPatterns = "/*", filterName = "filterDemo1",
        initParams = {@WebInitParam(name = "blacklist",value = "捣蛋鬼")})
public class FilterDemo1 implements Filter {

    private FilterConfig config;
    private  String blackList;
    private String ipblock;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init....");
        this.config = filterConfig;
        ipblock = config.getInitParameter("ipblock");
        blackList = config.getInitParameter("blacklist");
        System.out.println("blacklist initParam: "+blackList);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("filter dofilter.....");
        if(!checkRemoteIP(request,response)){
            return;
        }
        if(!checkUsername(request,response)){
            return;
        }
        long start = System.currentTimeMillis();
        chain.doFilter(request,response);
        long end = System.currentTimeMillis();

        String name = "";
        if(request instanceof HttpServletRequest){
            name = ((HttpServletRequest) request).getRequestURI();
        }
        System.out.println("Filter :"+name+": "+(end-start)+"ms");
    }

    private boolean checkUsername(ServletRequest request, ServletResponse response) throws IOException {
        String username = request.getParameter("username");
        if(username!=null && username.indexOf(blackList) != -1){
            //在获得响应输入流之前，设置编码格式。因为响应头的默认编码为ISO，获得的是iso编码格式的输入流，
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("<h1>对不起 "+username+",你没有权限留言 </h1>");
            writer.flush();
            return false;
        }
        return true;
    }

    private boolean checkRemoteIP(ServletRequest request, ServletResponse response) {
        return true;
    }

    @Override
    public void destroy() {
        System.out.println("Filter destory.....");
        config = null;
    }
}
